package com.internship.javawebinternship.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.internship.javawebinternship.entity.Account;
import com.internship.javawebinternship.entity.DailyReport;
import com.internship.javawebinternship.entity.LeaveApply;
import com.internship.javawebinternship.entity.StudentInfo;
import com.internship.javawebinternship.repository.AccountRepository;
import com.internship.javawebinternship.repository.LeaveApplyRepository;
import com.internship.javawebinternship.repository.StudentInfoRepository;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/leaveApply")
public class LeaveApplyController {
    AccountController accountController = new AccountController();
    @Autowired
    private LeaveApplyRepository leaveApplyRepository;
    @Autowired
    private AccountRepository accountRepository;
    @Autowired
    private StudentInfoRepository studentInforesp;

    @PostMapping("submitApply")//学生端提交离校申请
    public Object submitApply(HttpServletRequest request, @RequestBody String frontEnd) {

        Map<String, Object> result = new HashMap<>();
        HttpSession session = request.getSession(false);

        if (forceLogOut(request)) {
            result.put("result", "-1");
            result.put("msg", "您的账号已在其他地方登录，您已被强制下线。若需要继续操作，请重新登录并注意账号安全");
            JSONObject object = new JSONObject(result);
            return object;
        }

        String no;
        try {
            no = (String) session.getAttribute("no");
        } catch (NullPointerException e) {
            result.put("result", "0");
            result.put("msg", "您似乎尚未登录，请登录后重试");
            JSONObject object = new JSONObject(result);
            return object;
        }

        JSONObject receiveJSON = JSONObject.parseObject(frontEnd);
        if (receiveJSON.size() == 0) {
            result.put("result", "0");
            result.put("msg", "参数错误");
            JSONObject object = new JSONObject(result);
            return object;
        }

        String leavetime = receiveJSON.getString("leavetime");
        String reason = receiveJSON.getString("reason");
        String travelpath = receiveJSON.getString("travelpath");
        String traffic = receiveJSON.getString("traffic");

        LeaveApply leaveApply = new LeaveApply();
        try {
            leaveApply.setStuno(no);
            leaveApply.setLeavetime(leavetime);
            leaveApply.setReason(reason);
            leaveApply.setTravelpath(travelpath);
            leaveApply.setTraffic(traffic);
            leaveApply.setState("0");
            leaveApply.setComment("");
            leaveApplyRepository.save(leaveApply);
            result.put("result", "1");
            result.put("msg", "提交成功");
        } catch (Exception e) {
            result.put("result", "0");
            result.put("msg", "提交似乎出现了点问题");
            e.printStackTrace();
        }
        JSONObject object = new JSONObject(result);
        return object;
    }

    @PostMapping("getSubmitList")//学生端查看自己的离校记录
    public Object getSubmitList(HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        HttpSession session = request.getSession(false);

        if (forceLogOut(request)) {
            result.put("result", "-1");
            result.put("msg", "您的账号已在其他地方登录，您已被强制下线。若需要继续操作，请重新登录并注意账号安全");
            JSONObject object = new JSONObject(result);
            return object;
        }

        String stuno;
        try {
            stuno = (String) session.getAttribute("no");
        } catch (NullPointerException e) {
            result.put("result", "0");
            result.put("msg", "您似乎尚未登录，请登录后重试");
            JSONObject object = new JSONObject(result);
            return object;
        }

        Map<String, Object> result2 = new HashMap<>();

        Object res = leaveApplyRepository.findByStunoOrderByStateAsc(stuno);
        Object[] obj = new Object[((ArrayList<?>) res).size()];
        try {
            for (int i = 0; i < ((ArrayList<?>) res).size(); i++) {
                LeaveApply leaveApply = leaveApplyRepository.findByStunoOrderByStateAsc(stuno).get(i);
                Account account = accountRepository.findByStuempno(stuno).get(0);
                StudentInfo studentInfo = studentInforesp.findByStuno(stuno);

                result.clear();
                result.put("no", leaveApply.getStuno());
                result.put("name", account.getName());
                result.put("college", studentInfo.getCollege());
                result.put("class", studentInfo.getProfession() + studentInfo.getGrade() + "-" + studentInfo.getClasses());
                //学生的学院、专业班级信息
                result.put("travelpath", leaveApply.getTravelpath());
                result.put("leavetime", leaveApply.getLeavetime());
                result.put("state", leaveApply.getState());
                result.put("comment", leaveApply.getComment());
                result.put("traffic",leaveApply.getTraffic());
                result.put("reason",leaveApply.getReason());
                result.put("applyid",leaveApply.getApplyid());
                result2.put("result", "1");
                obj[i] = JSON.toJSON(result);

            }
        } catch (Exception e) {
            result2.clear();
            result2.put("result", "0");
            result2.put("msg", "似乎并没有离校数据");
            JSONObject object = new JSONObject(result2);
            return object;
        }
        result2.put("data", obj);
        JSONObject object = new JSONObject(result2);
        return object;
    }

    @PostMapping("deleteById")//删除离校申请记录
    public Object deleteById(@RequestBody String frontEnd, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        HttpSession session = request.getSession(false);

        if (forceLogOut(request)) {
            result.put("result", "-1");
            result.put("msg", "您的账号已在其他地方登录，您已被强制下线。若需要继续操作，请重新登录并注意账号安全");
            JSONObject object = new JSONObject(result);
            return object;
        }

        try {
            session.getAttribute("no");
        } catch (NullPointerException e) {
            result.put("result", "0");
            result.put("msg", "您似乎尚未登录，请登录后重试");
            JSONObject object = new JSONObject(result);
            return object;
        }

        JSONObject receiveJSON = JSONObject.parseObject(frontEnd);
        if (receiveJSON.size() == 0) {
            result.put("result", "0");
            result.put("msg", "参数错误");
            JSONObject object = new JSONObject(result);
            return object;
        }
        int applyid = receiveJSON.getIntValue("applyid");

        int flag = leaveApplyRepository.deleteByApplyid(applyid);
        if (flag != 0) {
            result.put("result", "1");
            result.put("msg", "删除成功");
        } else {
            result.put("result", "0");
            result.put("msg", "操作有误，删除失败");
        }
        JSONObject object = new JSONObject(result);
        return object;
    }

    @PostMapping("findAll")//管理员查询所有离校记录,按学号升序
    public Object findAll(HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        HttpSession session = request.getSession(false);

        if (forceLogOut(request)) {
            result.put("result", "-1");
            result.put("msg", "您的账号已在其他地方登录，您已被强制下线。若需要继续操作，请重新登录并注意账号安全");
            JSONObject object = new JSONObject(result);
            return object;
        }

        try {
            if (!session.getAttribute("authority").equals("0")) {
                result.put("result", "0");
                result.put("msg", "很抱歉，您无权限进行本操作，请联系管理员以获得帮助");
                JSONObject object = new JSONObject(result);
                return object;
            }
        } catch (NullPointerException e) {
            result.put("result", "0");
            result.put("msg", "您似乎尚未登录，请登录后重试");
            JSONObject object = new JSONObject(result);
            return object;
        }

        Map<String, Object> result2 = new HashMap<>();
        Object res = leaveApplyRepository.findAll();
        Object[] obj = new Object[((ArrayList<?>) res).size()];
        try {
            for (int i = 0; i < ((ArrayList<?>) res).size(); i++) {
                LeaveApply leaveApply = leaveApplyRepository.findAll().get(i);
                String no = leaveApply.getStuno();
                Account account = accountRepository.findByStuempno(no).get(0);
                StudentInfo studentInfo = studentInforesp.findByStuno(no);

                result.clear();
                result.put("applyid",leaveApply.getApplyid());
                result.put("no", leaveApply.getStuno());
                result.put("name", account.getName());
                result.put("college", studentInfo.getCollege());
                result.put("class", studentInfo.getProfession() + studentInfo.getGrade() + "-" + studentInfo.getClasses());
                result.put("reason", leaveApply.getReason());
                result.put("travelpath", leaveApply.getTravelpath());
                result.put("leavetime", leaveApply.getLeavetime());
                result.put("state", leaveApply.getState());
                result.put("comment", leaveApply.getComment());

                result2.put("result", "1");
                obj[i]=JSON.toJSON(result);
            }
        } catch (Exception e) {
            result2.clear();
            result2.put("result", "0");
            result2.put("msg", "查询遇到了异常");
            JSONObject object = new JSONObject(result2);
            return object;
        }
        result2.put("data", obj);
        JSONObject object = new JSONObject(result2);
        return object;
    }

    @PostMapping("findPart")//辅导员管理其权限范围内的学生的离校数据
    public Object findPart(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        HttpSession session = request.getSession(false);

        if (forceLogOut(request)) {
            result.put("result", "-1");
            result.put("msg", "您的账号已在其他地方登录，您已被强制下线。若需要继续操作，请重新登录并注意账号安全");
            JSONObject object = new JSONObject(result);
            return object;
        }

        String empNo ="";
        try {
            if (session.getAttribute("authority").equals("2") || session.getAttribute("authority").equals("3")) {
                result.put("result", "0");
                result.put("msg", "很抱歉，您无权限进行本操作，请联系管理员以获得帮助");
                JSONObject object = new JSONObject(result);
                return object;
            }
            empNo = (String) session.getAttribute("no");
        } catch (NullPointerException e) {
            result.put("result", "0");
            result.put("msg", "您似乎尚未登录，请登录后重试");
            JSONObject object = new JSONObject(result);
            return object;
        }

//        JSONObject receiveJSON = JSONObject.parseObject(frontEnd);
//        if (receiveJSON.size() == 0) {
//            result.put("result", "0");
//            result.put("msg", "参数错误");
//            JSONObject object = new JSONObject(result);
//            return object;
//        }

        Map<String, Object> result2 = new HashMap<>();

        Object res = leaveApplyRepository.findPart(empNo);
        Object[] obj = new Object[((ArrayList<?>) res).size()];
        if (!((ArrayList<?>) res).isEmpty()) {
            try {
                for (int i = 0; i <((ArrayList<?>) res).size(); i++) {
                    LeaveApply leaveApply = leaveApplyRepository.findPart(empNo).get(i);
                    String no = leaveApply.getStuno();
                    StudentInfo studentInfo = studentInforesp.findByStuno(no);
                    Account account = accountRepository.findByStuempno(no).get(0);

                    result.clear();
                    result.put("applyid",leaveApply.getApplyid());
                    result.put("no", leaveApply.getStuno());
                    //学生姓名
                    result.put("name", account.getName());
                    //学生的学院、专业班级信息
                    result.put("college", studentInfo.getCollege());
                    result.put("class", studentInfo.getProfession() + studentInfo.getGrade() + "-" + studentInfo.getClasses());
                    result.put("reason", leaveApply.getReason());
                    result.put("traffic",leaveApply.getTraffic());
                    result.put("travelpath", leaveApply.getTravelpath());
                    result.put("leavetime", leaveApply.getLeavetime());
                    result.put("state", leaveApply.getState());
                    result.put("comment", leaveApply.getComment());

                    result2.put("result", "1");
                    obj[i]=JSON.toJSON(result);
                }
            } catch (Exception e) {
                result2.clear();
                result2.put("result", "0");
                JSONObject object = new JSONObject(result2);
                return object;
            }
        } else {
            result2.clear();
            result2.put("result", 0);
            result2.put("msg", "似乎查询不到你的学生的数据");
            JSONObject object = new JSONObject(result2);
            return object;
        }

        result2.put("data", obj);
        JSONObject object = new JSONObject(result2);
        return object;
    }

    @PostMapping("getSubmit")
    public Object getSubmit(@RequestBody String frontEnd, HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        HttpSession session = request.getSession(false);

        if (forceLogOut(request)) {
            result.put("result", "-1");
            result.put("msg", "您的账号已在其他地方登录，您已被强制下线。若需要继续操作，请重新登录并注意账号安全");
            JSONObject object = new JSONObject(result);
            return object;
        }

        try {
            session.getAttribute("no");
        } catch (NullPointerException e) {
            result.put("result", "0");
            result.put("msg", "您似乎尚未登录，请登录后重试");
            JSONObject object = new JSONObject(result);
            return object;
        }

        JSONObject receiveJSON = JSONObject.parseObject(frontEnd);

        if (receiveJSON.size() == 0) {
            result.put("result", "0");
            result.put("msg", "参数错误");
            JSONObject object = new JSONObject(result);
            return object;
        }
        int applyid = receiveJSON.getIntValue("applyid");
        session.setAttribute("applyid", applyid);

        LeaveApply leaveApply = leaveApplyRepository.findByApplyid(applyid).get(0);
        String stuno = leaveApply.getStuno();
        String name = accountRepository.findByStuempno(stuno).get(0).getName();

        try {
            result.put("applyid",leaveApply.getApplyid());
            result.put("stuno", leaveApply.getStuno());
            result.put("name",name);
            result.put("leavetime", leaveApply.getLeavetime());
            result.put("reason", leaveApply.getReason());
            result.put("travelpath", leaveApply.getTravelpath());
            result.put("traffic", leaveApply.getTraffic());

        } catch (Exception e) {
            result.put("result", 0);
            JSONObject object = new JSONObject(result);
            return object;
        }
        JSONObject object = new JSONObject(result);
        return object;
    }

    @PostMapping("modifySubmit")//学生修改自己的审批
    public Object modifySubmit(HttpServletRequest request, @RequestBody String frontEnd) {
        Map<String, Object> result = new HashMap<>();
        HttpSession session = request.getSession(false);

        if (forceLogOut(request)) {
            result.put("result", "-1");
            result.put("msg", "您的账号已在其他地方登录，您已被强制下线。若需要继续操作，请重新登录并注意账号安全");
            JSONObject object = new JSONObject(result);
            return object;
        }

        String no;
        try {
            no = (String) session.getAttribute("no");
        } catch (NullPointerException e) {
            result.put("result", "0");
            result.put("msg", "您似乎尚未登录，请登录后重试");
            JSONObject object = new JSONObject(result);
            return object;
        }

        JSONObject receiveJSON = JSONObject.parseObject(frontEnd);
        if (receiveJSON.size() == 0) {
            result.put("result", "0");
            result.put("msg", "参数错误");
            JSONObject object = new JSONObject(result);
            return object;
        }
        int applyid = (int) session.getAttribute("applyid");
        session.removeAttribute("applyid");
        String leavetime = receiveJSON.getString("leavetime");
        String reason = receiveJSON.getString("reason");
        String travelpath = receiveJSON.getString("travelpath");
        String traffic = receiveJSON.getString("traffic");

        try {
            LeaveApply leaveApply = leaveApplyRepository.findByApplyid(applyid).get(0);
            //leaveApply.setStuno(no);
            leaveApply.setLeavetime(leavetime);
            leaveApply.setReason(reason);
            leaveApply.setTravelpath(travelpath);
            leaveApply.setTraffic(traffic);
//            leaveApply.setState(null);
//            leaveApply.setComment(null);
            leaveApplyRepository.save(leaveApply);
        } catch (Exception e) {
            result.put("result", "0");
            result.put("msg", "修改失败");
            JSONObject object = new JSONObject(result);
            return object;
        }

        result.put("result", "1");
        result.put("msg", "修改成功");
        JSONObject object = new JSONObject(result);
        return object;
    }

    @PostMapping("copeApply")//辅导员审批离校申请
    public Object copeApply(@RequestBody String frontEnd, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        HttpSession session = request.getSession(false);

        if (forceLogOut(request)) {
            result.put("result", "-1");
            result.put("msg", "您的账号已在其他地方登录，您已被强制下线。若需要继续操作，请重新登录并注意账号安全");
            JSONObject object = new JSONObject(result);
            return object;
        }

        try {
            if (session.getAttribute("authority").equals("2") || session.getAttribute("authority").equals("3")) {
                result.put("result", "0");
                result.put("msg", "很抱歉，您无权限进行本操作，请联系管理员以获得帮助");
                JSONObject object = new JSONObject(result);
                return object;
            }
        } catch (NullPointerException e) {
            result.put("result", "0");
            result.put("msg", "您似乎尚未登录，请登录后重试");
            JSONObject object = new JSONObject(result);
            return object;
        }

        JSONObject receiveJSON = JSONObject.parseObject(frontEnd);
        if (receiveJSON.size() == 0) {
            result.put("result", "0");
            result.put("msg", "参数错误");
            JSONObject object = new JSONObject(result);
            return object;
        }

        int applyid = receiveJSON.getIntValue("applyid");
        String state = receiveJSON.getString("state");
        String comment = receiveJSON.getString("comment");

        try {
            LeaveApply leaveApply = leaveApplyRepository.findByApplyid(applyid).get(0);
            leaveApply.setState(state);
            leaveApply.setComment(comment);
            leaveApplyRepository.save(leaveApply);
        } catch (Exception e) {
            result.put("result", "0");
            result.put("msg", "处理失败");
            JSONObject object = new JSONObject(result);
            return object;
        }

        result.put("result", "1");
        result.put("msg", "处理完成");
        JSONObject object = new JSONObject(result);
        return object;
    }

    public boolean forceLogOut(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        boolean status;
        try {
            if (session == null) {
                status = false;
                return status;
            }
            if (!session.getId().equals(accountRepository.findByStuempno((String) session.getAttribute("no")).get(0).getSessionid())) {
                status = true;
                session.invalidate();
            } else {
                status = false;
            }
        } catch (Exception e) {
            status = true;
            session.invalidate();
            return status;
        }
        return status;
    }
}






